function create_bg_contextMenus(){

  console.log("生成右侧菜单拓展")

  for(let key in menubar_datas){
    
    menudata = {
      type:"normal",
      title:menubar_datas[key]['title'],
      contexts:["all"],
      id:key
    }

    if(menubar_datas[key]['parentid'] != ""){
      menudata["parentId"] = menubar_datas[key]['parentid']
    }

    chrome.contextMenus.create(menudata,function(){

    })
  }

  
}

function create_time_chose_btns(menus_mod){

  console.log("添加时间选择")

  menus_colt_time_str = `<div class="time_controls" style="height: 35px;display: flex;flex-direction: row;">
    <div id="control_start_time_mod" style="position: relative;width: 320px;height: 100%;">
      <input type="date" id="control_start_time">
      <span id="control_start_time_text">选择开始时间</span>
    </div>
    <div id="control_end_time_mod" style="position: relative;">
      <input type="date" id="control_end_time">
      <span id="control_end_time_text">选择截止时间</span>
    </div>
  </div>`

  menus_p_colt_time_mod = document.createElement("div")
  menus_p_colt_time_mod.innerHTML = menus_colt_time_str;
  

  menus_colt_time_mod = menus_p_colt_time_mod.querySelector("div")
  // console.log(menus_colt_time_mod)
  // console.log(menus_colt_time_mod.querySelector("#control_start_time"))

  menus_colt_time_mod.querySelector("#control_start_time").addEventListener("change",function(){

    menus_colt_time_mod.querySelector("#control_start_time_text").textContent = `${this.value} 00:00:00`

  })
  
  

  menus_colt_time_mod.querySelector("#control_end_time").addEventListener("change",function(){

    menus_colt_time_mod.querySelector("#control_end_time_text").textContent = `${this.value} 23:59:59`

  })

  menus_mod.querySelector(".controls").appendChild(menus_colt_time_mod)


}


function create_meuns_btns(menus_mod){

  console.log("添加菜单按钮")

  menus_colt_search_str = `<div class="search_controls" style="height: 35px;"></div>`  
  menus_p_colt_search_mod = document.createElement("div")
  menus_p_colt_search_mod.innerHTML = menus_colt_search_str;

  menus_colt_search_mod = menus_p_colt_search_mod.querySelector("div")
  

  
  for(let key in menubar_datas){
    btn_mod = document.createElement("a")
    btn_mod.id = menubar_datas[key]['id']
    btn_mod.dataset['bind_set'] = menubar_datas[key]['id']
    btn_mod.dataset['barname'] = menubar_datas[key]['title']
    btn_mod.textContent = menubar_datas[key]['title']
    btn_mod.style.marginRight = '12px';

    btn_mod.addEventListener('click',function(){
      analysis(this)
    })

    menus_colt_search_mod.appendChild(btn_mod)
  }

  menus_mod.querySelector(".controls").appendChild(menus_colt_search_mod)
}

function create_top_menus(){

  menus_mod_str = `<div style="height: 85px; display: flex; flex-direction: row;flex-wrap: wrap;align-items: center;padding: 2px 23px;"><span>拓展:</span><div class="controls" style=" width: 94%;margin-left: 20px; padding-top: 16px;"></div></div>`
  menus_p_mod = document.createElement("div")
  menus_p_mod.innerHTML = menus_mod_str;
  menus_mod = menus_p_mod.querySelector("div")

  create_time_chose_btns(menus_mod) // 添加时间
  create_meuns_btns(menus_mod)

  
  document.querySelector('body').insertBefore(menus_mod,document.querySelector("#root"))

  // document.querySelector("#control_start_time").addEventListener("change",function(){

  //   menus_colt_time_mod.querySelector("#control_start_time_text").textContent = `${this.value} 00:00:00`
  // })
  // document.querySelector("#control_end_time").addEventListener("change",function(){
  //   menus_colt_time_mod.querySelector("#control_end_time_text").textContent = `${this.value} 23:59:59`
    
  // })
  

}


function getCookie(name){
  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
  
  if(arr != null)
      return unescape(arr[2]);
  return null;
  
}

/**
 * 请求crm数据
 * @param {*} url 需要请求的链接 
 * @param {*} respone_data post请求带的参数
 * @param {*} key key\keyname 用于存入指定数据列
 * @param {*} callback 回调
 */
function requestData(url,respone_data,key,callback){

  // console.log(respone_data)
  authorization = getCookie("crm_da_jsessionid")

  $.ajax({
    type:"post",
    url:url,
    data:respone_data,
    datatype:"json",
    headers:{
      "authorization": authorization,
      "content-type": "application/json"
    },
    success:function(res){
      callback({
        key:key,
        data:res.data
      })
    }
  })
}

// 点击指定数据按钮分析数据
function analysis(mod){


  console.log("开始分析数据")


  // 显示弹窗，并设置位置为加载中
  
  console.log(document.querySelector("#table_iframe"))
  table_iframe = document.querySelector("#table_iframe")
  table_iframe_bg = document.querySelector("#table_iframe_bg")
  table_iframe.style.display = 'block'
  table_iframe_bg.style.display = 'block'

  table_iframe_win = document.querySelector("#table_iframe").contentWindow
  table_iframe_dom = table_iframe.contentDocument


  
  table_iframe_searchbtn = table_iframe_dom.querySelector("#table_iframe_searchbtn")
  table_iframe_searchbtn.textContent = '数据加载中....,请稍后'


  console.log(mod)

  barname = mod.dataset['barname']

  start_day = document.querySelector("#control_start_time_text").textContent
  end_day = document.querySelector("#control_end_time_text").textContent

  if(start_day == "选择开始时间" || end_day == "选择截止时间"){
    alert("请选择开始和结束日期")
    return;
  }

  data_mods = analysis_sets[mod.dataset['bind_set']] //根据按钮绑定的对应参数，找到参数设置
  // console.log(data_mods)

  sf_list = ["本页合计","安徽","北京","福建","甘肃","广东","广西","贵州","海南","河北","河南","黑龙江","湖北","湖南","吉林","江苏","江西","辽宁","内蒙古","宁夏","青海","山东","山西","陕西","上海","四川","天津","新疆","云南","浙江","重庆","网校"]

  all_datas = {}
  all_datas['sfname'] = sf_list

  data_mods_len = data_mods.length
  has_cl_len = 0

  // 遍历参数设置 生成数据
  data_mods.map(data_mod=>{
    // console.log(data_mod)
    data = data_mod['data']
    data['start_day'] = start_day
    data['end_day'] = end_day

    respone_data = JSON.stringify(data)

    url = data_mod['searchReport_link']
    key = data_mod['key']
    key_name = data_mod['keyname']
    // console.log(key)
    // console.log(key_name)
    key_d = {
      "key":key,
      "key_name":key_name
    }

    all_datas[key_name] = []

    requestData(url,respone_data,key_d,res=>{

      // console.log(res)
      res.data.map(item=>{

        sf_list.map(sfname=>{

          if(item.province_orgname.includes(sfname)){
            sf_list_index = sf_list.indexOf(sfname)

            // 如果包含省份，在省份对应的位置插入 对应的数据
            // 因为请求回影响全局key和key_name的值所以通过出安茹获取
            all_datas[res.key.key_name][sf_list_index] = item[res.key.key]
            // console.log(all_datas[key])
            
          }
        })

      })
      
        
      has_cl_len++;
      // console.log(has_cl_len)
    })
  })

  
  listen_anaylsis = setInterval(function(){

    if(has_cl_len>= data_mods_len){
      console.log(all_datas)

      sf_list = all_datas['sfname']

      table_datas = []
      columns_data = []
      for(let i=0;i<sf_list.length;i++){

        table_data = {}
        for(t_key in all_datas){
          table_data[t_key] = all_datas[t_key][i]
        }
        table_datas.push(table_data)



      }

      for(t_key in all_datas){

        columns_data.push({
          "field":t_key,
          "title":t_key,
        })
      }
      console.log(table_datas)
      console.log(columns_data)

      // 将获取的数据存入缓存
      localStorage.setItem('table_name',barname)
      localStorage.setItem('table_datas',JSON.stringify(table_datas))
      localStorage.setItem('columns_data',JSON.stringify(columns_data))

      // create_iframe_table()
      clearInterval(listen_anaylsis)

      // 点击iframe中的生成按钮
      table_iframe_searchbtn.click()
      table_iframe_searchbtn.textContent = '数据加载完成,点击右边的小按钮即可下载文档'


    }

  },500)
}

create_iframe_table()
// console.log(document.querySelector("#table_iframe"))

function create_iframe_table(){

  var table_iframe_bg = $(`<div id="table_iframe_bg" style="display:none;position: fixed;width: 100%;height: 100%;background: black;top: 0;opacity: 0.4;z-index: 1;"></div>`)
  table_iframe_bg.bind('click',function(){
    $("#table_iframe_bg").hide();
    $("#table_iframe").hide();
  })
  console.log(table_iframe_bg)
  $('body').append(table_iframe_bg)
  
  var table_iframe = document.createElement('iframe')
  table_iframe.id = "table_iframe"
  table_iframe.style.display = 'none';

  table_iframe.style.width = '800px';
  table_iframe.style.height = '600px';
  table_iframe.style.position = 'fixed';
  table_iframe.style.left = '50%';
  table_iframe.style.top = '50%';
  table_iframe.style.marginLeft = '-400px';
  table_iframe.style.marginTop = '-300px';
  table_iframe.style.zIndex = '2';

  document.querySelector("body").appendChild(table_iframe)
  iframe_win = table_iframe.contentWindow

  iframe_win.addEventListener("load",function(){
    console.log(this)
  })


  iframe_win.document.open();
  iframe_win.document.write('<!DOCTYPE html>');
  iframe_win.document.write('<html>');
  iframe_win.document.write('<head>');
  iframe_win.document.write('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />');

  iframe_win.document.write(`<script src="https://www.zglinxuan.com/statics/js/public/jquery-2.0.0.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://www.zglinxuan.com/statics/js/table/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://www.zglinxuan.com/statics/js/table/bootstrap-table.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://www.zglinxuan.com/statics/js/table/bootstrap-table-zh-CN.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://www.zglinxuan.com/statics/js/table/bootstrap-datetimepicker.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://www.zglinxuan.com/statics/js/table/bootstrap-datetimepicker.zh-CN.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://www.zglinxuan.com/statics/js/table/bootstrap-table-export.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://www.zglinxuan.com/statics/js/table/tableExport.min.js" type="text/javascript" charset="utf-8"></script>
  <link rel="stylesheet" type="text/css" href="https://www.zglinxuan.com/statics/css/table/bootstrap.min.css"/>
  <link rel="stylesheet" type="text/css" href="https://www.zglinxuan.com/statics/css/table/bootstrap-table.min.css"/>
  <link rel="stylesheet" type="text/css" href="https://www.zglinxuan.com/statics/css/table/bootstrap-datetimepicker.min.css"/>`)

  iframe_win.document.write('</head>');

  iframe_win.document.write('<body>');
  iframe_win.document.write('<div><a onclick="search_data()" id="table_iframe_searchbtn">测试</a></div>');
  

  iframe_win.document.write('<table id="table" data-export-options="{\'fileName\': \'products\', \'worksheetName\': \'products\'}"></table>');
  iframe_win.document.write('</body>');

  iframe_win.document.write(`
  <script>
    function loadTable(search_data,columns,showExport,fileName){
      $('#table').bootstrapTable('load', search_data);
      $('#table').bootstrapTable('destroy').bootstrapTable({
        toolbar: "#toolbar", //指定工具栏
        toolbarAlign: "center", //工具栏对齐方式
        // pagination: true, //是否分页
        // pageSize: 10, //单页记录数
        // pageList: [5, 10, 20, 50], //分页步进值
        // showColumns: true, //列选择按钮
        showExport: showExport, //是否显示导出按钮
        filename: "全部数据导出",
        buttonsAlign: "right", //按钮位置
        exportDataType: "all", //导出类型
        // search: true, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        // strictSearch: 'phone',
        locale: "zh-CN", //中文支持
        exportTypes: ['excel'], //导出文件类型
        Icons: 'glyphicon-export',
            exportOptions: {
                    fileName: fileName,  //文件名称设置
                    worksheetName: 'sheet1',  //表格工作区名称
                    tableName: fileName,
                    excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
                },
        columns: columns,
        data: search_data
      })
    }
    function search_data(){
      table_datas = JSON.parse(localStorage.getItem('table_datas'))
      columns_data = JSON.parse(localStorage.getItem('columns_data'))
      
      table_name = localStorage.getItem('table_name')

      console.log(table_datas)
      console.log(columns_data)
      loadTable(table_datas,columns_data,1,table_name)
    }
  </script>
  `)

  iframe_win.document.write('</html>');
  iframe_win.document.close();

}


